<template>
	<div class="monitorDispatch">
		<div class="dispatchBox" v-loading="dispatchLoading">
      <el-form ref="dispatchForm" label-position="right" :model="dispatchForm" :rules="formRules" size="mini" class="dispatchForm">
        <el-row>
          <el-col :span="21">
            <el-form-item label="调度时间" prop="time" label-width="110px">
              <el-date-picker
                style="width:100%"
                v-model="dispatchForm.time"
                type="datetime"
                placeholder="选择日期时间"
                default-time="12:00:00"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="21">

          <el-form-item label="调度地点" prop="address" label-width="110px" class="requiredClass">
            <el-col :span="8">
              <el-form-item label="" prop="district">
                <el-select
                  style="width: 100%;"
                  v-model="dispatchForm.district" 
                  placeholder="市" 
                  value-key="name"
                  @change="search">
                  <p v-for="(item, index) of citySelectList" :key="index">
                    <el-option :label="item.name" :value="item"></el-option>
                  </p>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="" prop="are">
                <el-select v-model="dispatchForm.are" placeholder="请选择区" value-key="name" @change="search" style="width: 100%;">
                  <p v-for="(item, index) of areaSelectList" :key="index">
                    <el-option :label="item.name" :value="item"></el-option>
                  </p>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="" prop="street">
                <el-select v-model="dispatchForm.street" placeholder="请选择街道" value-key="name" @change="search" style="width: 100%;">
                  <p v-for="(item, index) of streetSelectList" :key="index">
                    <el-option :label="item.name" :value="item"></el-option>
                  </p>
                </el-select>
              </el-form-item>
            </el-col>
          
            <el-col :span="24">
              <el-form-item label="">
                <el-input v-model="dispatchForm.detailAddr" placeholder="选填 详细地址" style="width:100%"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="21">
            <el-form-item label="调度车辆编号" prop="vehicleId" label-width="110px">
              <el-select v-model="dispatchForm.vehicleId" placeholder="请选择车辆编号" @change="selectChange"  style="width:100%" disabled>
                <p v-for="(item, index) of vehicleNumList" :key="index">
                  <el-option :label="item.name" :value="item.name"></el-option>
                </p>
              </el-select>
            </el-form-item>
            <el-form-item label="调度车牌号" label-width="110px" prop="plateNumber">
              <el-input v-model="dispatchForm.plateNumber" style="width:100%" disabled></el-input>
            </el-form-item>
            
          </el-col>
        </el-row>
      </el-form>

      <!-- <div class="divider"></div> -->

      <div class="submitBox">
        <el-button type="primary" size="small" @click="onSubmit('dispatchForm')" class="greenBtn submitBtn">确定</el-button>
      </div>
    
    </div>
	</div>
</template>
<script>
import MapLoader from "../plugins/AMap.js";
import {mapActions,mapGetters} from 'vuex'
// import common from '@/plugins/common'
export default {
  name: 'monitorDispatch',
  data () {
    return {
      msg: 'hello monitorDispatch!',
      selCondition: [],
      dispatchLoading: false,
      dispatchForm: {
        vehicleId: '',
        time: '',
        plateNumber: '',
        district: "",
        are: "",
        street: "",
        detailAddr: "",
      },
      formRules: {
        time: [
          { type: 'string', required: true, message: '请选择时间', trigger: 'change' }
        ],
        vehicleId: [
          { required: true, message: '请选择车辆编号', trigger: 'change' }
        ],
        plateNumber: [
          { required: true, message: '请选择车辆编号', trigger: 'change' }
        ],
        address: [
          { required: false, message: '请选择正确的市区街道', trigger: 'change' }
        ],
        district: [
          { required: true, message: '请选择市', trigger: 'change' }
        ],
        are: [
          { required: true, message: '请选择区', trigger: 'change' }
        ],
        street: [
          { required: true, message: '请选择街道', trigger: 'change' }
        ],
      },
      district: null, //行政区搜索实例对象
      citySelectList: [],
      areaSelectList: [],
      streetSelectList: [],
		}
  },
  async created() {
    this.dispatchLoading = true

    
    this.dispatchForm.person = this.userInfo.user.username
    this.dispatchForm.identity = this.userInfo.user.identity
    this.dispatchForm.phone = this.userInfo.user.phone

    this.dispatchForm.vehicleId = this.vehicleNumList[0].name
    this.dispatchForm.plateNumber = this.vehicleNumList[0].number

    this.districtSearchInit()
    this.dispatchLoading = false
  },
	methods: {
    ...mapActions([
      'submitDispatch',
      'getDispatchSelect',
    ]),
    selectChange(name) {
      let vehicleNumList = this.vehicleNumList
      let curSel = vehicleNumList.find(v => v.name === name)
      this.dispatchForm.plateNumber = curSel.number
    },
    onSubmit(formName) {
      const that = this
      const dispatchForm = that.dispatchForm
      that.$refs[formName].validate(async (valid) => {
        if(valid) {
          const h = this.$createElement;
          const fullAddr = dispatchForm.district.name + dispatchForm.are.name + dispatchForm.street.name + dispatchForm.detailAddr
          that.$msgbox({
            title: '提示',
            message: h('p', null, [
              h('p', {style: "text-indent: 4em;"}, '调度地点：' + fullAddr),
              h('p', {style: "text-indent: 4em;"}, '调度时间：' + dispatchForm.time),
              h('p', {style: "text-indent: 4em;"}, '调度车辆编号：' + dispatchForm.vehicleId),
              h('p', {style: "text-indent: 4em;"}, '提交人：' + this.userInfo.user.username),
              h('br', null, ''),
              h('h4', {style: "text-align: center;font-weight: bold;"}, '请确认调度信息'),
            ]),
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(async () => {
            that.dispatchLoading = true
            let result = await that.submitDispatch({
              address: fullAddr,
              time: dispatchForm.time,
              vehicle: dispatchForm.vehicleId
            })
            if(result.message === 'success') {
              that.$notify({
                title: '成功',
                message: '调度成功，已发送信息给运维人员',
                type: 'success'
              });
              that.$refs.dispatchForm.resetFields();
              if(!that.userInfo.roles.includes('manager')) {
                that.$router.push('/monitorDispatchList')
              }
            }else {
              that.$notify({
                title: '失败',
                message: result.info,
                type: 'error'
              });
            }
            that.dispatchLoading = false
          });
          
        }else {
          return false;
        }
      })
    },
    districtSearchInit() {
      //行政区划查询
      let opts = {
        subdistrict: 1,   //返回下一级行政区
        showbiz: false  //最后一级返回街道信息
      };
      MapLoader().then(
        AMap => {
          this.district = new AMap.DistrictSearch(opts);//注意：需要使用插件同步下发功能才能这样直接使用
          this.district.search('广东省', (status, result) => {
            if(status == 'complete'){
              this.getData(result.districtList[0], 'province');
            }
          });
        },
        e => {
        }
      )
      
    },
    getData(data,level) {
      // debugger
      
      let subList = data.districtList;

      //清空下一级别的下拉列表
      if(level === 'province') {
        this.citySelectList = subList
        this.areaSelectList = []
        this.streetSelectList = []
      }else if (level === 'city') {
        this.areaSelectList = subList
        this.streetSelectList = []
      } else if (level === 'district') {
        this.streetSelectList = subList
      }
        
    },
    search(obj) {
      // debugger
      var adcode = obj.adcode;
      let level = obj.level

      // district.setLevel(option.level); //行政区级别
      //行政区查询
      //按照adcode进行查询可以保证数据返回的唯一性
      this.district.search(adcode, (status, result) => {
        if(status === 'complete'){
          this.getData(result.districtList[0], level);
        }
      });
    }
  },
  computed: {
    ...mapGetters({
      vehicleNumList: 'getVehicleNumList',
      userInfo: 'getUserInfo'
    })
  }
}
</script>
<style scoped>
.monitorDispatch {
  background: #fff;
  min-height: 100%;
}
.dispatchBox {
  padding: 20px;
}
.dispatchForm{
  max-width: 600px;
}
.dispatchForm label {
  font-weight: bold;
}

.dispatchForm >>> .el-form-item__label{
  font-weight: bold;
}

.submitBox {
  display: inline-block;
  position: relative;
  left: 110px;
}
.divider {
  width: 100%;
  height: 1px;
  background: #dcdcdc;
  margin: 15px 0;
}

</style>
<style>

.requiredClass .el-form-item__label::before {
  content: "* ";
  color: #F56C6C;
}
</style>
